package com.xywy.wjk.widget;

import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.xywy.R;

/**
 * 血压效果展示：
 */
public class BloodPresureView extends LinearLayout {

	public static final int REFRESH_VIEW = 0;
	Paint numericalPaint; // 高低压数值
	Paint viewPaint; // 展示柱体view
	Paint textPaint; // 展示柱体view

	Bitmap highBarBitmap; // 高压柱
	Bitmap lowBarBitmap;// 低压柱
	Bitmap bottomBitmap; // 底座

	Timer timer;
	TimerTask task;
	int lowProgress = 1;
	int highProgress = 1;
	
	int finalLowProgress = 1;
	int finalHighProgress = 1;
	//120 60;

	View view;
	private final float BPPERDP = 1.375f; // 医用血压计最高压力为165; 为血压计高压留下空间为120dp；
   
	private float normalMaxValue = 120; //下降到的高压
	private float normalMinValue = 60;//下降到的低压
	
	private boolean heigh2lowSwitch = false;
	// 可计算出，每dp代表血压值2.5
	
	Timer finalTimer;

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public BloodPresureView(Context context, AttributeSet arg1, int arg2) {
		super(context, arg1, arg2);
		init(context);
	}

	public BloodPresureView(Context context, AttributeSet arg1) {
		super(context, arg1);
		init(context);
	}

	public BloodPresureView(Context context) {
		super(context);
		init(context);
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	private TextView tv_highCount; //
	private TextView tv_lowCount;
	private TextView tv_content;
	private ImageView iv_highBar;
	private ImageView iv_lowBar;
	private Button btn_startPresure;
	private LinearLayout ll_click;
	private Context mContext;

	private Handler handler;
	private Activity activity;
	DecimalFormat df = new DecimalFormat("0");

	/**
	 * 初始化自定义控件；
	 * 
	 * @param context
	 */
	private void init(Context context) {
		mContext = context;
		view = View.inflate(context, R.layout.blood_presure_view, this);
		tv_content = (TextView) view.findViewById(R.id.tv_content);
		tv_highCount = (TextView) view.findViewById(R.id.tv_highCount);
		tv_lowCount = (TextView) view.findViewById(R.id.tv_lowCount);
		iv_highBar = (ImageView) view.findViewById(R.id.iv_highBar);
		iv_lowBar = (ImageView) view.findViewById(R.id.iv_lowBar);
		ll_click = (LinearLayout) view.findViewById(R.id.ll_click);
		btn_startPresure = (Button) view.findViewById(R.id.btn_startPresure);

	}

	/**
	 * 设置当前开始按钮的状态
	 */
	public void setBtnState(boolean enable) {
		if (enable) {
			btn_startPresure
					.setBackgroundResource(R.drawable.blood_presure_btn_normal);
		} else {
			btn_startPresure
					.setBackgroundResource(R.drawable.blood_presure_btn_pressed);
//			btn_startPresure.setText("正在测量中");
		}
		btn_startPresure.setEnabled(enable);
	}
	
	public void setBtnText(String text){
		btn_startPresure.setText(text);
	}

	/**
	 * 立即体验按钮的点击事件；
	 */
	OnClickListener btnl;//开始测量按钮
	OnClickListener lll;//按钮以上部分

	/**
	 * 测量出当前的结果后展示
	 * 
	 * @param result
	 */
	public  void setTestResult(String result) {
		tv_content.setText(result);
	}

	/**
	 * 设置立即体验点击事件
	 */
	public void setBtnOnClickListener(OnClickListener l) {
		this.btnl = l;
		btn_startPresure.setOnClickListener(btnl);
	}

	/**
	 * 设置
	 * 
	 * @param l
	 */
	public void setLlOnClickListener(OnClickListener l) {
		this.lll = l;
		ll_click.setOnClickListener(lll);
	}

	/**
	 * 设置当前数值；
	 * 
	 * @param high
	 * @param low
	 */
	public void setHightAndLowNum(float high, float low) {
		if (high < 0 || high >= 300 || low < 0 || low >= 300) {
			return;
		}
			highProgress = (int) (high / BPPERDP);
			lowProgress = (int) (low / BPPERDP);
			if(highProgress > 120){
				highProgress = 120;
				high = 165;
			}
			if(lowProgress >120){
				low = 165;
				lowProgress = 120;
			}
			haha();
			tv_highCount.setText(df.format(high) + "");
			tv_lowCount.setText(df.format(low) + "");
	}
	
	/**
	 * 最终的动画
	 */
	void endPresure(){
		finalTimer = new Timer();
		finalTimer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				if(lowProgress < finalLowProgress){
					lowProgress++;
				}else if (lowProgress> finalLowProgress) {
					lowProgress--;
				}else {
					lowProgress = finalLowProgress;
				}
				
				if(highProgress < finalHighProgress){
					highProgress++;
				}else if(highProgress > finalHighProgress){
					highProgress--;
				}else {
					highProgress = finalHighProgress;
				}
				if(finalHighProgress == highProgress && finalLowProgress ==lowProgress){
					finalTimer.cancel();
				}
				haha();
			}
		}, 0,100);
	}

	/**
	 * 开始测量了，我需要一个动画，提示用户已经测量；
	 */
	public void startPresure() {
		// TODO 第三个参数需要计算；
        if(timer != null ){
        	timer.cancel();
        }
		timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				if(heigh2lowSwitch){
					if(lowProgress > 44){
						lowProgress--;
					}
					if(highProgress>88){
						highProgress--;
					}
					
					if(highProgress == 88 && lowProgress == 44){
//						timer.cancel();
					}
					
				}else {
					if (lowProgress < 120) {
						lowProgress++;
					}
					if (highProgress < 120) {
						highProgress++;
					}
					if (lowProgress == 120 && highProgress == 120 && timer != null) {
//						timer.cancel();
						heigh2lowSwitch = true ;
					}
				}
				haha();

			}
		}, 0, 100);
	}

	public void setActivity(Activity activity) {
		this.activity = activity;
	}

	public void haha() {
		activity.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				System.out.println("activity.runOnUiThread(new Runnable() {   "
						+ lowProgress + "   " + highProgress);
				android.widget.RelativeLayout.LayoutParams highParams = new android.widget.RelativeLayout.LayoutParams(
						dip2px(mContext, 80), dip2px(mContext, highProgress));

				highParams.rightMargin = dip2px(mContext, 20);
				highParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
				highParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
				iv_highBar.setLayoutParams(highParams);
				tv_highCount.setText(df.format(highProgress * BPPERDP) + "");

				android.widget.RelativeLayout.LayoutParams lowParams = new android.widget.RelativeLayout.LayoutParams(
						dip2px(mContext, 80), dip2px(mContext, lowProgress));
				lowParams.leftMargin = dip2px(mContext, 20);
				lowParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
				lowParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				iv_lowBar.setLayoutParams(lowParams);
				tv_lowCount.setText(df.format(lowProgress * BPPERDP) + "");
			}
		});

	}

	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		int measureWidth = measureWidth(widthMeasureSpec);
		int measureHeight = measureHeight(heightMeasureSpec);
		// 计算自定义的ViewGroup中所有子控件的大小
		measureChildren(widthMeasureSpec, heightMeasureSpec);
		// 设置自定义的控件MyViewGroup的大小
		setMeasuredDimension(measureWidth, measureHeight);
		// setWorth(this.lowProgress, this.highProgress);
	}

	private int measureWidth(int pWidthMeasureSpec) {
		int result = 0;
		int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);// 得到模式
		int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);// 得到尺寸

		switch (widthMode) {
		/**
		 * mode共有三种情况，取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY,
		 * MeasureSpec.AT_MOST。
		 * 
		 * 
		 * MeasureSpec.EXACTLY是精确尺寸，
		 * 当我们将控件的layout_width或layout_height指定为具体数值时如andorid
		 * :layout_width="50dip"，或者为FILL_PARENT是，都是控件大小已经确定的情况，都是精确尺寸。
		 * 
		 * 
		 * MeasureSpec.AT_MOST是最大尺寸，
		 * 当控件的layout_width或layout_height指定为WRAP_CONTENT时
		 * ，控件大小一般随着控件的子空间或内容进行变化，此时控件尺寸只要不超过父控件允许的最大尺寸即可
		 * 。因此，此时的mode是AT_MOST，size给出了父控件允许的最大尺寸。
		 * 
		 * 
		 * MeasureSpec.UNSPECIFIED是未指定尺寸，这种情况不多，一般都是父控件是AdapterView，
		 * 通过measure方法传入的模式。
		 */
		case MeasureSpec.AT_MOST:
		case MeasureSpec.EXACTLY:
			result = widthSize;
			break;
		}
		return result;
	}

	private int measureHeight(int pHeightMeasureSpec) {
		int result = 0;

		int heightMode = MeasureSpec.getMode(pHeightMeasureSpec);
		int heightSize = MeasureSpec.getSize(pHeightMeasureSpec);

		switch (heightMode) {
		case MeasureSpec.AT_MOST:
		case MeasureSpec.EXACTLY:
			result = heightSize;
			break;
		}
		return result;
	}
}
